package com.feige.controller;

import com.feige.constant.Constants;
import com.feige.entity.SecurityUser;
import com.feige.pojo.vo.FrontRouteVo;
import com.feige.pojo.dto.LoginFormDto;
import com.feige.result.AjaxResult;
import com.feige.service.IndexService;
import com.feige.service.PermissionService;
import com.feige.utils.common.Admin;
import com.feige.utils.jwt.JwtInfo;
import com.feige.utils.jwt.JwtUtils;
import com.feige.utils.redis.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Set;

/**
 * @author feige
 */
@Api(tags = "主控制器类")
@RestController
@RequestMapping("/admin")
public class IndexController {

    @Resource
    private IndexService indexService;

    @Resource
    private PermissionService permissionService;

    @Resource
    private RedisUtils redisUtils;

    @Value("${download.path}")
    private String path;

    /**
     * 登录方法
     *
     * @param loginFormDto 登录表单
     * @return 结果
     */
    @ApiOperation(value="登录")
    @PostMapping("/login")
    public AjaxResult login(@Validated @RequestBody LoginFormDto loginFormDto)   {
        String token = indexService.login(loginFormDto.getUsername(), loginFormDto.getPassword(), loginFormDto.getCode(), loginFormDto.getUuid());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("token",token);
        return ajax;
    }


    @ApiOperation(value = "获取用户的菜单")
    @GetMapping("/menu")
    public AjaxResult getMenu(HttpServletRequest request){
        JwtInfo jwtInfo = JwtUtils.getJwtInfoByJwtToken(request);
        List<FrontRouteVo> menu = indexService.getMenu(jwtInfo);
        //System.out.println(menu);
        return AjaxResult.success(menu);
    }

    @ApiOperation(value = "获取用户的信息")
    @GetMapping("/info")
    public AjaxResult getInfo(HttpServletRequest request){
        String username = JwtUtils.getUsernameAndNumFromToken(request.getHeader(Constants.TOKEN_KEY));
        SecurityUser securityUser = (SecurityUser)redisUtils.get(Constants.LOGIN_USER_KEY + username);
        //Set<String> permissions = securityUser.getPermissions();
        Set<String> roles = securityUser.getRoles();
        Set<String> permissions;

        if (Admin.isAdmin(securityUser.getCurrentUser().getNum())){
            permissions = permissionService.selectAllPermissionValue();
        }else {
            permissions = permissionService.selectPermissionValueByUserId(securityUser.getCurrentUser().getId());
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user",securityUser.getCurrentUser());
        ajax.put("permissions",permissions);
        ajax.put("roles",roles);
        return ajax;
    }

    @ApiOperation(value = "通用下载方法")
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse resp ) throws IOException {
        File file = new File(path + File.separatorChar + fileName);
        InputStream is = new FileInputStream(file);
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("multipart/form-data");
        resp.setHeader("Content-Disposition",
                "attachment;fileName=" + fileName);
        ServletOutputStream os = resp.getOutputStream();
        int len;
        byte[] bytes = new byte[1024];
        while ((len = is.read(bytes)) != -1){
            os.write(bytes,0,len);
        }
    }
}
